package com.shuo.map;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * LRU的简单实现--LinkedHashMap
 */
public class LRU_Linked extends LinkedHashMap<String, Integer> {
    private int capSize;

    public LRU_Linked(int capSize, boolean accessOrder) {
        super(capSize, 0.75F, accessOrder);
        this.capSize = capSize;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
        return size() > capSize;
    }

    public static void main(String[] args) {
        /* 插入顺序淘汰 */
        LRU_Linked uio = new LRU_Linked(3, false);
        uio.put("1", 1);
        uio.put("2", 2);
        uio.put("3", 3);
        uio.put("4", 4);
        uio.put("5", 5);
        /* 3 4 5 */
        for (String s : uio.keySet()) {
            System.out.println(s);
        }

        /* 访问顺序淘汰 */
        LRU_Linked uao = new LRU_Linked(3, true);
        uao.put("1", 1);
        uao.put("2", 2);
        uao.put("3", 3);
        uao.get("1");
        uao.put("4", 4);
        uao.put("5", 5);
        /* 1 4 5 */
        for (String s : uao.keySet()) {
            System.out.println(s);
        }
    }
}
